package com.alibaba.algo.core.base;

import com.alibaba.algo.core.req.HttpRequestDTO;
import com.alibaba.algo.core.resp.HttpResponseDTO;
import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: glorysongglory
 * Date: 2020/11/16
 * Time: 10:42
 */
@Component
public class HttpComponnent {

    @Autowired
    private RestTemplate restTemplate;

    public <T> HttpResponseDTO<T> doGet(HttpRequestDTO requestDTO, Class<T> responseType) {
        Map<String, Object> paraMap = requestDTO.getParamMap();
        String url = requestDTO.getUrl();
        StringBuffer stringBuffer = new StringBuffer();
        String paraUrl = "";
        if(!CollectionUtils.isEmpty(paraMap)) {
        	Iterator iterator = paraMap.entrySet().iterator();
            if (iterator.hasNext()) {
                stringBuffer.append("?");
                Object element;
                while (iterator.hasNext()) {
                    element = iterator.next();
                    Map.Entry<String, Object> entry = (Map.Entry) element;
                    //过滤value为null，value为null时进行拼接字符串会变成 "null"字符串
                    if (entry.getValue() != null) {
                        stringBuffer.append(element).append("&");
                    }
                    paraUrl = stringBuffer.substring(0, stringBuffer.length() - 1);
                }
            }
        }
        ResponseEntity<T> responseEntity = restTemplate.getForEntity(url + paraUrl, responseType);
        HttpResponseDTO<T> responseDTO = new HttpResponseDTO<>();
        responseDTO.setHeaders(responseEntity.getHeaders());
        responseDTO.setHttpStatus(responseEntity.getStatusCode());
        responseDTO.setStatusCode(responseEntity.getStatusCodeValue());
        responseDTO.setResponseBody(responseEntity.getBody());
        return responseDTO;
    }

    public <T> HttpResponseDTO<T> doPost(HttpRequestDTO requestDTO, Class<T> responseType) {
        MediaType mediaType = requestDTO.getContentType();
        String url = requestDTO.getUrl();
        HttpHeaders postHeaders = new HttpHeaders();
        MultiValueMap<String, String> postParam = new LinkedMultiValueMap<>();
        if (null == mediaType) {
            postHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        }else {
        	postHeaders.setContentType(mediaType);
        }

        // 处理header
        Map<String, Object> paramHeaderMap = requestDTO.getHeaderParaMap();
        if(!CollectionUtils.isEmpty(paramHeaderMap)) {
        	Iterator iterator = paramHeaderMap.entrySet().iterator();
            if (iterator.hasNext()) {
                Object element;
                while (iterator.hasNext()) {
                    element = iterator.next();
                    Map.Entry<String, Object> entry = (Map.Entry) element;
                    postHeaders.add(entry.getKey(), String.valueOf(entry.getValue()));
                    if(HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(entry.getKey())) {
                    	postHeaders.setContentType(MediaType.valueOf(String.valueOf(entry.getValue())));
                    }
                }
            }
        }
        HttpEntity<?> request = null;
        //处理body
        Map<String, Object> paramBodeyMap = requestDTO.getParamMap();
        if(postHeaders.getContentType().isCompatibleWith(MediaType.APPLICATION_JSON)) {
        	request = new HttpEntity<>(JSON.toJSONString(paramBodeyMap), postHeaders);
        }else {
        	if(!CollectionUtils.isEmpty(paramBodeyMap)) {
            	Iterator iteratorbody = paramBodeyMap.entrySet().iterator();
                if (iteratorbody.hasNext()) {
                    Object element;
                    while (iteratorbody.hasNext()) {
                        element = iteratorbody.next();
                        Map.Entry<String, Object> entry = (Map.Entry) element;
                        postParam.add(entry.getKey(), String.valueOf(entry.getValue()));
                    }
                }
            }
        	request = new HttpEntity<MultiValueMap<String, String>>(postParam, postHeaders);
        }
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, request, responseType);
        HttpResponseDTO<T> responseDTO = new HttpResponseDTO<>();
        responseDTO.setHeaders(responseEntity.getHeaders());
        responseDTO.setHttpStatus(responseEntity.getStatusCode());
        responseDTO.setStatusCode(responseEntity.getStatusCodeValue());
        responseDTO.setResponseBody(responseEntity.getBody());
        return responseDTO;
    }


}
